package com.xj.exportfile.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.luciad.imageio.webp.WebPReadParam;
import com.xj.exportfile.entity.User;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class PdfUtils {

    //处理中文显示问题，使用资源字体
    private static BaseFont bfChinese;
    static {
        try {
            bfChinese = BaseFont.createFont("/font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 设置三种字体大小
    private final static Font max = new Font(bfChinese, 14, Font.BOLD);
    private final static Font normal = new Font(bfChinese, 10, Font.NORMAL);
    private final static Font min = new Font(bfChinese, 7, Font.NORMAL);
    // 设置行高
    private final static float lineHeight = (float) 25.0;
    // 设置图片高度
    private final static int imageHeight = 300;
    // 设置合并单元格
    private final static int colSpan = 1;
    private final static int rowSpan = 1;

    /**
     * 生成”码上巡察“ PDF
     * @param vo
     * @param response
     * @throws Exception
     */
    public static ByteArrayOutputStream export(User vo) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 创建文档
        Document document = new Document();
        // 给出输出路径
        PdfWriter.getInstance(document, outputStream);
        // 打开文档
        document.open();
        // 标题
        PdfPTable tableTitle = new PdfPTable(3);
        // 生成一个5列的表格
        PdfPTable table = new PdfPTable(4);
        // 设置表格总体宽度
        tableTitle.setWidthPercentage(100);
        table.setWidthPercentage(100);
        // 添加标题
        createTableCellCenter("", normal, tableTitle, lineHeight, colSpan);
        createTableCellCenter("用户信息表", max, tableTitle, lineHeight, colSpan);
        createTableCellRight("\n" + "用户编号:" + vo.getId() + "\n" + "反映时间:" + DateUtil.format(vo.getCreateTime(), "yyyy-MM-dd HH:mm:ss"),
                min, tableTitle, lineHeight, colSpan);
        document.add(tableTitle);
        document.add(new Paragraph("\n"));
        // 设置反映人
        createTableCell("姓名", normal, table, lineHeight, colSpan, rowSpan);
        createTableCell(StrUtil.emptyToDefault(vo.getName(), "/"), normal, table, lineHeight, colSpan, rowSpan);
        createTableCell("性别", normal, table, lineHeight, colSpan, rowSpan);
        createTableCell(StrUtil.emptyToDefault(vo.getSex(), "/"), normal, table, lineHeight, colSpan, rowSpan);
        createTableCell("联系方式", normal, table, lineHeight, colSpan, rowSpan);
        createTableCell(StrUtil.emptyToDefault(vo.getPhone(), "/"), normal, table, lineHeight, colSpan, rowSpan);
        createTableCell("住址", normal, table, lineHeight, colSpan, rowSpan);
        createTableCell(StrUtil.emptyToDefault(vo.getAddress(), "/"), normal, table, lineHeight, colSpan, rowSpan);
        createTableCell("工作类型", normal, table, lineHeight, colSpan, rowSpan);
        createTableCell(vo.getWork(), normal, table, lineHeight, 3, rowSpan);
        createTableCell("个人简介", normal, table, lineHeight, colSpan, rowSpan);
        createTableCellLeft(vo.getProfile(), normal, table, lineHeight, 3, rowSpan);
        // 附件
        String[] images = vo.getImages().split(",");
        createTableCell("个人图片", normal, table, lineHeight, colSpan, Math.max(images.length, 1));
        for (String image : images) {
            if (StrUtil.isNotEmpty(image)) {
                try {
                    createTableCellImage(image, table, imageHeight, 4, rowSpan);
                } catch (IOException e) {
                    createTableCellImage(webpToJpeg(image), table, imageHeight, 4, rowSpan);
                }
            }
        }
        document.add(table);
        document.close();
        return outputStream;
    }

    /**
     * 插入图片
     *
     * @param images
     * @param table
     * @param imageHeight
     * @param colSpan
     * @param rowSpan
     * @throws BadElementException
     * @throws IOException
     */
    private static void createTableCellImage(String images, PdfPTable table, int imageHeight, int colSpan, int rowSpan) throws BadElementException, IOException {
        Image certImg = Image.getInstance(images);
        PdfPCell cell = new PdfPCell();
        cell.setImage(certImg);
        // 合并单元格列
        cell.setColspan(colSpan);
        cell.setRowspan(rowSpan);
        // 设置水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        // 设置垂直居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        // 设置宽度
//        cell.setFixedHeight(imageHeight);
        // 将单元格内容添加到表格中
        table.addCell(cell);
    }

    /**
     * 往表格中插入
     *
     * @param text
     * @param font
     * @param table
     * @param lineHeight
     * @param colSpan
     * @param rowSpan
     */
    private static void createTableCell(String text, Font font, PdfPTable table, float lineHeight, int colSpan, int rowSpan) {
        PdfPCell cell;
        cell = new PdfPCell(new Paragraph(text, font));
        //合并单元格列
        cell.setColspan(colSpan);
        cell.setRowspan(rowSpan);
        //设置水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setMinimumHeight(lineHeight);
        //将单元格内容添加到表格中
        table.addCell(cell);
    }

    /**
     * 设置无边框表格并靠左显示
     *
     * @param text
     * @param font
     * @param table
     * @param lineHeight
     * @param colSpan
     */
    private static void createTableCellLeft(String text, Font font, PdfPTable table, float lineHeight, int colSpan, int rowSpan) {
        PdfPCell cell;
        cell = new PdfPCell(new Paragraph(text, font));
        //合并单元格列
        cell.setColspan(colSpan);
        cell.setRowspan(rowSpan);
        //设置水平
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        //设置垂直
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setMinimumHeight(lineHeight);
        //将单元格内容添加到表格中
        table.addCell(cell);
    }

    /**
     * 设置无边框表格并居中显示
     *
     * @param text
     * @param font
     * @param table
     * @param lineHeight
     * @param colSpan
     */
    private static void createTableCellCenter(String text, Font font, PdfPTable table, float lineHeight, int colSpan) {
        PdfPCell cell;
        cell = new PdfPCell(new Paragraph(text, font));
        //合并单元格列
        cell.setColspan(colSpan);
        //设置水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setFixedHeight(lineHeight);
        cell.setBorderWidthLeft(0);
        cell.setBorderWidthRight(0);
        cell.setBorderWidthBottom(0);
        cell.setBorderWidthTop(0);
        //将单元格内容添加到表格中
        table.addCell(cell);

    }

    /**
     * 设置无边框表格并靠右显示
     *
     * @param text
     * @param font
     * @param table
     * @param lineHeight
     * @param colSpan
     */
    private static void createTableCellRight(String text, Font font, PdfPTable table, float lineHeight, int colSpan) {
        PdfPCell cell;
        cell = new PdfPCell(new Paragraph(text, font));
        //合并单元格列
        cell.setColspan(colSpan);
        //设置水平
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        //设置垂直
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.setFixedHeight(lineHeight);
        //将单元格内容添加到表格中
        //去除边框
        cell.setBorderWidthLeft(0);
        cell.setBorderWidthBottom(0);
        cell.setBorderWidthRight(0);
        cell.setBorderWidthTop(0);
        table.addCell(cell);
    }

    /**
     * webp 图片转 jpeg
     * @param webpPath
     * @throws IOException
     */
    public static String webpToJpeg(String webpPath) throws IOException {
        // 创建临时文件
        File file = new File("tmp/webp2Jpeg.jpeg");
        // 初始化参数
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();
        WebPReadParam readParam = new WebPReadParam();
        readParam.setBypassFiltering(true);
        // 将图片转为 jpeg
        reader.setInput(ImageIO.createImageInputStream(Utilities.toURL(webpPath).openStream()));
        BufferedImage image = reader.read(0, readParam);
        ImageIO.write(image, "jpeg", file);
        return file.getPath();
    }
}
